// Copyright(c) gert.cuykens@gmail.com
// experimental testing http://nodejs.org
var fs = require('fs')
var http = require('http')

var buf=function(res,fd,i,s,buffer){
 if(i+buffer.length<s){
  fs.read(fd,buffer,0,buffer.length,i,function(e,l,b){
   res.write(b.slice(0,l))
   //console.log(b.toString('utf8',0,l))
   buf(res,fd,i+buffer.length,s,buffer)
  })
 }
 else{
  fs.read(fd,buffer,0,buffer.length,i,function(e,l,b){
   res.end(b.slice(0,l))
   fs.close(fd)
  })
 }
}

var app = function(req,res){
 var head={'Content-Type':'text/html'}
 switch(req.url.slice(-3)){
  case '.js':head={'Content-Type':'text/javascript'};break;
  case 'css':head={'Content-Type':'text/css'};break;
  case 'png':head={'Content-Type':'image/png'};break;
  case 'ico':head={'Content-Type':'image/x-icon'};break;
  case 'ogg':head={'Content-Type':'audio/ogg'};break;
  case 'ebm':head={'Content-Type':'video/webm'};break;
 }
 head['Transfer-Encoding']='chunked'
 res.writeHead(200,head)
 console.log('.'+req.url+' '+head['Content-Type'])
 fs.open('.'+req.url,'r',function(err,fd){
  fs.fstat(fd,function(err, stats){
   var buffer = new Buffer(100)
   buf(res,fd,0,stats.size,buffer)
  })
 })
}

http.createServer(app).listen(8000,"127.0.0.1")
console.log('GET http://127.0.0.1:8000/appwsgi/www/index.htm')

/*
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('appwsgi/db.bin');
var out = ''
db.serialize(function() {
 db.each("SELECT uid FROM users", function(err, row) {out+=row.uid+' '});
 db.close();
})

req.on('data',function(){})

var file_stream = fs.createReadStream('.'+req.url)
file_stream.on("error", function(exception){console.error("Error reading file: ",exception)})
file_stream.on("data",function(data){res.write(data)})
file_stream.on("close",function(){res.end()})

head['Content-Length']=stats.size
head['Accept-Ranges']='bytes'
head['Etag']=''
req.headers.if-none-match -> 304
req.headers.if-modified-since -> 304
var range = req.headers.range
range = range?/bytes=([0-9]+)-([0-9]*)/.exec(range):range
var start = range?parseInt(range[1],10):0
var end = range?parseInt(range[2],10):stats.size-1
head['Content-Range']='bytes '+start+'-'+end+'/'+stats.size
res.writeHead(206,head)
*/

